<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="根据名称" prop="isVerified">
        <el-input
            v-model="queryParams.name"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
        <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            :icon="Plus"
            @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            :icon="Delete"
            @click="handleDelete"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table v-loading="loading" :data="doctorsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="医生编号" align="center" width="100" type="index" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="性别" align="center" prop="gender">
        <template #default="{ row }">
          {{ row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column label="电话号" align="center" prop="phone" />
      <el-table-column label="医院" align="center" prop="hospitall.name"/>
      <el-table-column label="科室" align="center" prop="bigdep.name"/>
      <el-table-column label="职务" align="center" prop="title" />
      <el-table-column label="问诊资金" align="center" prop="price" />
      <!--      <el-table-column label="创建时间" align="center" prop="lastLoginTime" width="180">-->
      <!--        <template #default="{ row }">-->
      <!--          {{ formatDate(row.lastLoginTime) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <!--      <el-table-column label="修改时间" align="center" prop="registrationTime" width="180">-->
      <!--        <template #default="{ row }">-->
      <!--          {{ formatDate(row.registrationTime) }}-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="患者数量" align="center" prop="isVerified" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{ row }">
          <el-button
              type="primary"
              link
              :icon="Edit"
              @click="showAll(row)"
          >查看</el-button>
          <!--          <el-button-->
          <!--              type="primary"-->
          <!--              link-->
          <!--              :icon="Delete"-->
          <!--              @click="handleDelete(row)"-->
          <!--          >删除</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-if="total > 0"
        v-model:current-page="queryParams.currentPage"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[1, 3, 10, 20]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />


    <el-dialog
        v-model="open"
        :title="title"
        width="500px"
        append-to-body
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="医生姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入医生姓名" />
        </el-form-item>
        <el-form-item label="医生头像" prop="avatar">
          <el-upload
              class="avatar-uploader"
              action="/api/doctor/upload"
              :show-file-list="false"
              :headers="{ 'token': token }"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="问诊金额" prop="price">
          <el-input-number v-model="form.price" :min="1" :max="100">
            <template #prefix>
              <span>￥</span>
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="所属医院" prop="hospitalId">
          <el-select
              v-model="form.hospitalId"
              placeholder="请选择医院"
              clearable
              @change="handleHospitalChange"
              filterable
          >
            <el-option
                v-for="item in hospitalOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="科室" prop="departmentId">
          <el-select
              v-model="form.departmentId"
              placeholder="请选择科室"
              clearable
              filterable
          >
            <el-option
                v-for="item in departmentOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="form.title" placeholder="请输入职称">
            <el-option label="主任" value="主任" />
            <el-option label="副主任" value="副主任" />
            <el-option label="医师" value="医师" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Edit, Delete} from '@element-plus/icons-vue'
import { listDoctors, delDoctors, addDoctors, updateDoctors ,getBigdep,getHospition} from '../../api/doctors/doctors.js'
import router from "../../router/index.js";

// 遮罩层
const loading = ref(true)
// 选中数组
const ids = ref([])
// 非多个禁用
const multiple = ref(true)
// 显示搜索条件
const showSearch = ref(true)
// 总条数
const total = ref(0)
// 医生表格数据
const doctorsList = ref([])
// 弹出层标题
const title = ref('')
// 是否显示弹出层
const open = ref(false)
// 表单ref
const formRef = ref()
// 查询表单ref
const queryFormRef = ref()
const operationType = ref('add')

// 医院选项
const hospitalOptions = ref([])
const getHospital = async () => {
  try {
    const res = await getHospition()
    console.log('完整的医院响应:', res)
    console.log('医院数据类型:', typeof res)

    if (res && res.data && Array.isArray(res.data)) {
      hospitalOptions.value = res.data
      console.log('设置后的医院选项:', hospitalOptions.value)
    } else {
      hospitalOptions.value = []
      console.warn('未获取到医院数据')
      ElMessage.warning('暂无医院数据')
    }
  } catch (error) {
    console.error('获取医院列表失败:', error)
    hospitalOptions.value = []
    ElMessage.error('获取医院列表失败')
  }
}

// 科室选项
const departmentOptions = ref([])
const getBigdepp = async () => {
  try {
    const res = await getBigdep()
    console.log('完整的科室响应:', res)
    console.log('科室数据类型:', typeof res)

    if (res && res.data && Array.isArray(res.data)) {
      departmentOptions.value = res.data
      console.log('设置后的科室选项:', departmentOptions.value)
    } else {
      departmentOptions.value = []
      console.warn('未获取到科室数据')
      ElMessage.warning('暂无科室数据')
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    departmentOptions.value = []
    ElMessage.error('获取科室列表失败')
  }
}


// 查询参数
const queryParams = ref({
  currentPage: 1,
  pageSize: 5,
  name: '',
  queryString:''
})
const selectQueryCondition = () => {
  if (queryParams.value.name) {
    queryParams.value.queryString = queryParams.value.name;
  } else {
    queryParams.value.queryString = null;
  }
};

// 表单参数
const form = reactive({
  id: undefined,
  name: '',
  gender: '1',
  phone: '',
  hospitalId: undefined,
  departmentId: undefined,
  price: 1,
  title: '',
  imgurl: ''
})

// 表单校验规则
const rules = {
  name: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  price: [{ required: true, message: '请输入问诊金额', trigger: 'blur' }],
  hospitalId: [{ required: true, message: '请选择所属医院', trigger: 'change' }],
  departmentId: [{ required: true, message: '请选择科室', trigger: 'change' }],
  title: [{ required: true, message: '请选择职称', trigger: 'change' }]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}

// 获取医生列表
const getList = async () => {
  selectQueryCondition()
  loading.value = true;
  try {
    const res = await listDoctors(queryParams.value);
    console.log('API Response:', res); // 调试日志

    if (res) {
      doctorsList.value = res.rows || [];
      total.value = res.total || 0;

      if (doctorsList.value.length === 0) {
        ElMessage.warning('暂无医生数据');
      }
    } else {
      doctorsList.value = [];
      total.value = 0;
      ElMessage.warning('获取数据失败，请检查网络连接');
    }
  } catch (error) {
    console.error('获取医生列表失败:', error);
    doctorsList.value = [];
    total.value = 0;
    ElMessage.error(error.message || '获取医生列表失败');
  } finally {
    loading.value = false;
  }
}

// 表单重置
const reset = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: undefined,
    name: '',
    gender: '1',
    phone: '',
    price: 1,
    hospitalId: undefined,
    departmentId: undefined,
    title: '',
    imgurl: ''
  })
  imageUrl.value = ''
  // 重新获取医院和科室列表
  getHospital()
  getBigdepp()
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.value.currentPage = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  // 重置查询参数
  queryParams.value = {
    currentPage: 1,
    pageSize: 5,
    name: '',
    queryString: ''
  }
  // 重新获取列表数据
  getList()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  multiple.value = !selection.length
}

// 新增按钮操作
// const data= ref({})
const handleAdd = async () => {
  reset()
  open.value = true
  title.value = '添加医生'
  operationType.value = 'add'
}

/**
 * 查看详情
 * @returns {Promise<void>}
 */
const showAll = (row) => {
  router.push({
    path: `/showxx/${row.id}`  // 路由参数方式
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    let res

    if (operationType.value === 'add') {
      res = await addDoctors(form)
      console.log('添加医生响应:', res) // 添加调试日志

      // 检查响应中的 flag 字段
      if (res && res.flag === true) {
        ElMessage.success(res.message || '添加成功')
        open.value = false
        getList()
      } else {
        ElMessage.error(res?.message || '添加失败，请检查数据后重试')
      }
    } else if (operationType.value === 'edit') {
      // 在发送请求前打印表单数据
      console.log('提交的表单数据:', JSON.stringify(form))

      res = await updateDoctors(form)

      // 详细打印响应结构
      console.log('更新医生完整响应:', res)

      // 根据实际响应格式修改判断条件
      if (res && res.flag === true) {
        ElMessage.success(res.message || '修改成功')
        open.value = false
        getList()
      } else {
        // 打印更详细的错误信息
        console.error('更新失败，响应:', res)
        ElMessage.error(res?.message || '修改失败，请检查数据后重试')
      }
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error(error.message || '操作失败，请稍后重试')
  }
}

// 删除操作
const handleDelete = async (row) => {
  const deleteIds = row?.id || ids.value;
  if (!deleteIds) {
    ElMessage.warning('请选择要删除的数据');
    return;
  }

  try {
    await ElMessageBox.confirm('是否确认删除选中的数据项？');
    const res = await delDoctors(deleteIds);

    if (res) {
      ElMessage.success('删除成功');
      getList();
    } else {
      ElMessage.error(res?.msg || '删除失败，请稍后重试');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error);
      ElMessage.error(error.message || '删除失败，请检查网络连接');
    }
  }
}

// 头像上传成功处理
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  form.imgurl = response.data
  console.log('上传响应:', response)
  ElMessage.success('头像上传成功')
}

// 验证头像上传
const beforeAvatarUpload = (rawFile) => {
  if (!rawFile) {
    ElMessage.error('请选择要上传的图片')
    return false
  }

  const isImage = rawFile.type === 'image/jpeg' || rawFile.type === 'image/png' || rawFile.type === 'image/jpg'
  const isLt2M = rawFile.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('头像必须是JPG、PNG或JPEG格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过2MB！')
    return false
  }
  return true
}

// 图片预览url
const imageUrl = ref('')

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}
/**
 * 分页
 */
// 添加分页处理方法
// 页面大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val;
  getList();
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.currentPage = val;
  getList();
}

// 医院选择改变处理
const handleHospitalChange = async (value) => {
  console.log('选择的医院ID:', value)
  // 当医院选择改变时，重置科室选择
  form.departmentId = undefined

  if (!value) {
    departmentOptions.value = []
    return
  }

  // 重新获取科室列表
  try {
    const res = await getBigdep(value)
    console.log('根据医院ID获取的科室数据:', res)

    if (res && res.data && Array.isArray(res.data)) {
      // 根据选中的医院ID过滤科室
      departmentOptions.value = res.data.filter(dept => dept.hospitalId === value)
      console.log('过滤后的科室选项:', departmentOptions.value)
    } else {
      departmentOptions.value = []
      ElMessage.warning('该医院暂无科室数据')
    }
  } catch (error) {
    console.error('获取科室列表失败:', error)
    departmentOptions.value = []
    ElMessage.error('获取科室列表失败')
  }
}

// 初始化数据
const initData = async () => {
  try {
    await getHospital()
    if (form.hospitalId) {
      await handleHospitalChange(form.hospitalId)
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 获取医院名称
const getHospitalName = (hospitalId) => {
  if (!hospitalId) return '-'
  const hospital = hospitalOptions.value.find(h => h.id === hospitalId)
  return hospital ? hospital.name : '-'
}

// 获取科室名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '-'
  const department = departmentOptions.value.find(d => d.id === departmentId)
  return department ? department.name : '-'
}

// 编辑按钮操作
const handleEdit = (row) => {
  reset()

  // 打印原始行数据
  console.log('原始行数据:', row)

  // 创建一个新对象，只包含需要的字段
  const formData = {
    id: row.id,
    name: row.name,
    gender: String(row.gender), // 确保性别是字符串类型
    phone: row.phone,
    price: row.price,
    title: row.title,
    imgurl: row.imgurl || '',
    // 如果需要，添加其他字段
    hospitalId: row.hospitall?.id,
    departmentId: row.bigdep?.id
  }

  // 打印处理后的表单数据
  console.log('处理后的表单数据:', formData)

  // 设置表单数据
  Object.assign(form, formData)

  // 设置头像URL
  imageUrl.value = row.imgurl || ''

  open.value = true
  title.value = '编辑医生'
  operationType.value = 'edit'
}

// 添加在其他 ref 变量附近
const token = ref(''); // 或者从你的认证系统中获取

// 在 onMounted 中获取 token
onMounted(() => {
  // 从localStorage或其他存储中获取token
  token.value = localStorage.getItem('token') || '';

  getList();
  initData();
})
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.mb8 {
  margin-bottom: 8px;
}
.dialog-footer {
  padding: 20px;
  text-align: right;
}
</style>
